package com.fang.study.lock;

import com.fang.study.util.ZkUtils;
import com.fang.study.watch.LockCallbackWatch;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description zookeeper分布式锁实现
 * @date 2022/7/7 11:18 上午
 **/
public class TestLock {
    private ZooKeeper zk;

    @Before
    public void getConn() {
        zk = ZkUtils.getZk();
    }

    @After
    public void close() throws InterruptedException {
        zk.close();
    }

    @Test
    public void lock() {
        for (int i = 0; i < 10; i++) {
            new Thread() {
                @Override
                public void run() {
                    LockCallbackWatch watch = new LockCallbackWatch(zk, Thread.currentThread().getName());
                    try {
                        // 抢锁
                        watch.tryLock();
                        // 执行逻辑
                        System.out.println("----执行代码逻辑----");
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    } finally {
                        // 释放锁
                        watch.unLock();
                    }
                }
            }.start();
        }
    }
}
